/*
 * added by shengdian
 * AttachEvent:监听Dom元素的事件
 *  
 *  target：监听对象
 *  eventName：监听函数类型，如click,mouseover
 *  handler：监听函数
 *  argsObject:参数
 */
function AttachEvent(target, eventName, handler, argsObject) {
	var eventHandler = handler;
	if (argsObject) {
		eventHander = function(e) {
			handler.call(argsObject, e);
		}
	}
	if (window.attachEvent)// IE
		target.attachEvent("on" + eventName, eventHander);
	else
		// FF
		target.addEventListener(eventName, eventHander, false);
}

/**
 * 数字检查，只允许数字及小数点，自动过滤非数字及小数点部分，baishuang402
 * 
 * @param num，过滤内容
 * @param decimal，小数位长度
 * @returns {String}
 */
function numberCheck(num, decimal) {
	oldString = num.value.split('');
	if (!decimal) {
		decimal = 2;
	}
	if (!(oldString == 'undefined')) {
		var newString = ''
		var pointCount = 0;
		var decimalLength = 0;
		for (i = 0; i < oldString.length; i++) {
			var oldStr = oldString[i];
			if (!isNaN(oldStr)) {
				if (pointCount != 0)
					decimalLength++;
				if (decimalLength <= decimal)
					newString += oldString[i]
			} else if ("." == oldStr) {
				if (pointCount == 0) {
					newString += oldString[i]
				}
				pointCount++;
			}
		}
		return newString;
	}
}

/*
 * addEventListener:监听Dom元素的事件
 * 
 * target：监听对象 type：监听函数类型，如click,mouseover func：监听函数
 */
function addEventHandler(target, type, func) {
	if (target.addEventListener) {
		// 监听IE9，谷歌和火狐
		target.addEventListener(type, func, false);
	} else if (target.attachEvent) {
		target.attachEvent("on" + type, func);
	} else {
		target["on" + type] = func;
	}
}
/*
 * removeEventHandler:移除Dom元素的事件
 * 
 * target：监听对象 type：监听函数类型，如click,mouseover func：监听函数
 */
function removeEventHandler(target, type, func) {
	if (target.removeEventListener) {
		// 监听IE9，谷歌和火狐
		alert(1);
		target.removeEventListener(type, func, false);
	} else if (target.detachEvent) {
		alert(2);
		target.detachEvent("on" + type, func);
	} else {
		alert(3);
		delete target["on" + type];
	}
}
// var notIE = -[1,];
var notIE = false;
window.onload = function() {
	if (-[ 1, ]) {
		// alert("这不是IE浏览器!");
	} else {
		notIE = true;
		// alert("这是IE浏览器!");
	}
	// alert("Init");
	var inputs = document.getElementsByTagName("INPUT");
	// alert(inputs.length);
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == "text"
				&& inputs[i].getAttribute('formatNumber') == "true") {
			// alert(inputs[i].type+inputs[i].getAttribute('formatNumber')+"------------"+inputs[i].id+"------------"+inputs[i].required);
			// do something
			if (inputs[i].value != null && inputs[i].value != ''
					&& inputs[i].value != "") {
				inputs[i].value = datagridFormatNumber(inputs[i].value)
			}else{
				inputs[i].value = "0.00";
			}
			AttachEvent(inputs[i], "change", formatNumber, inputs[i]);
			AttachEvent(inputs[i], "blur", blurNumber, inputs[i]);
			AttachEvent(inputs[i], "focus", focusNumber, inputs[i]);
		}

	}

}

/**
 * added by baishuang on 20160328
 * formatNumber()方法，参数一：需格式化的数字，参数二：保留的小数位数，参数三：格式化时的分隔符；
 * 可只传入金额，使用默认的保留两位小数，以逗号分隔的形式（例如：formatMoney(10000)，将返回：10,000.00）。
 */
function formatMoney(num, precision, separator) {
	var parts;
	// 判断是否为数字
	if (!isNaN(parseFloat(num)) && isFinite(num)) {
		// 把类似 .5, 5. 之类的数据转化成0.5, 5, 为数据精度处理做准, 至于为什么
		// 不在判断中直接写 if (!isNaN(num = parseFloat(num)) && isFinite(num))
		// 是因为parseFloat有一个奇怪的精度问题, 比如 parseFloat(12312312.1234567119)
		// 的值变成了 12312312.123456713
		num = Number(num);
		// 处理小数点位数
		num = (typeof precision !== 'undefined' ? num.toFixed(precision) : num
				.toFixed(2)).toString();
		// 分离数字的小数部分和整数部分
		parts = num.split('.');
		// 整数部分加[separator]分隔, 借用一个著名的正则表达式
		parts[0] = parts[0].toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,
				'$1' + (separator || ','));

		return parts.join('.') + ' 元';
	}
	return NaN;
}

function blurNumber(e) {
	var pattern = this.pattern;
	var num = this.value;
	if (num == null || num == '') {
		return
	}
	num = num.replace(new RegExp(/(,)/g), '');
	// alert("reg=="+num);
	$('#' + this.id).numberbox({
		min : 0,
		precision : 3,
		formatter : function(value) {
			return toNumber(num, pattern);
		}
	});
}

function focusNumber(e) {
	var num = this.value;
	$('#' + this.id).numberbox({
		min : 0,
		precision : 3,
		formatter : function(value) {
			return num.replace(new RegExp(/(,)/g), '');
		}
	});
}

/**
 * 格式化数字显示方式 用法 formatNumber(12345.999,'#,##0.00');
 * formatNumber(12345.999,'#,##0.##'); formatNumber(123,'000000');
 * 
 * @param num
 * @param pattern
 */
function formatNumber(e) {
	var sign = "";
	var width = this.style.width;
	if (notIE) {
		this.style.cssText = "text-align:right;width:" + width;// 文本右对齐
	} else {
		this.style = "text-align:right;align:right;width:" + width;// 文本右对齐
	}

	var pattern = this.pattern;
	var num = this.value;
	if (num == null || num == '') {
		return
	}
	num = num.replace(new RegExp(/(,)/g), '');
	num = parseFloat(num); 
	if(num != 'NaN' && num <0){
		sign = "-";
		num = -num;
		alert("金额数据为负数，请输入正数!");
		if (this.className.indexOf("easyui-numberbox") > -1) {
			$('#' + this.id).numberbox({
				formatter : function(value) {
					return "0";
				}
			});
		} else {
			$('#' + this.id).numberbox({
				min : 0,
				precision : 3,
				formatter : function(value) {
					return "0";
				}
			});
		}
		return "";
	}
	/*
	 * if(parseInt(num) == 0){ if (this.className.indexOf("easyui-numberbox") >
	 * -1) { $('#' + this.id).numberbox({ formatter : function(value) { return
	 * "0"; } }); } else { $('#' + this.id).numberbox({ min : 0, precision : 3,
	 * formatter : function(value) { return "0"; } }); } return ""; }
	 */
	num = num.toString();
	num = zeroFormat(num);// 去掉以0开头非个位数据
	if (isNaN(num) || num > Math.pow(10, 13)) {
		alert("金额数据过大,最大限额拾万亿（拾兆）!");
		if (this.className.indexOf("easyui-numberbox") > -1) {
			$('#' + this.id).numberbox({
				formatter : function(value) {
					return "0";
				}
			});
		} else {
			$('#' + this.id).numberbox({
				min : 0,
				precision : 3,
				formatter : function(value) {
					return "0";
				}
			});
		}
		return "";
	}
	num = toNumber(num, pattern);
	if (this.className.indexOf("easyui-numberbox") > -1) {
		$('#' + this.id).numberbox({
			formatter : function(value) {
				return sign+num;
			}
		});
	} else {
		$('#' + this.id).numberbox({
			min : 0,
			precision : 3,
			formatter : function(value) {
				return sign+num;
			}
		});
	}

	// this.innerHTML = toNumber(num,pattern);
// this.title = numberChar(num.replace(new RegExp(/(,)/g), ''));
	this.title = changeMoneyToChinese(num.replace(new RegExp(/(,)/g), ''));
// alert(this.title);
}
/**
 * 将千分位格式的数字字符串转换为浮点数
 * 
 * @public
 * @param string
 *            sVal 数值字符串
 * @return float
 */
function unFormatMoney(sVal){
	var fTmp = parseFloat(sVal.replace(/,/g, ''));
	return (isNaN(fTmp) ? 0 : fTmp);
}

function zeroFormat(num) {
	if (num.indexOf(".") > 0) {
		var strarr = num.toString().split('.');
		if (strarr[0].length == 1) {
			return num;
		} else {
			return zeroRp(strarr[0]) + "." + strarr[1];
		}
	} else {
		if (num.length == 1) {
			return num;
		} else {
			return zeroRp(num);
		}
	}
}

function zeroRp(number) {
	if (number.indexOf("0") == 0) {
		number = number.substring(1, number.length);
		number = zeroRp(number);
	}
	return number;
}

function toNumber(num, pattern) {
	if (pattern == null || pattern == '') {
		pattern = '#,##0.000';
	}
	var strarr = num ? num.toString().split('.') : [ '0' ];
	var fmtarr = pattern ? pattern.split('.') : [ '' ];
	var retstr = '';

	// 整数部分
	var str = strarr[0];
	var fmt = fmtarr[0];
	var i = str.length - 1;
	var comma = false;
	for (var f = fmt.length - 1; f >= 0; f--) {
		switch (fmt.substr(f, 1)) {
		case '#':
			if (i >= 0)
				retstr = str.substr(i--, 1) + retstr;
			break;
		case '0':
			if (i >= 0)
				retstr = str.substr(i--, 1) + retstr;
			else
				retstr = '0' + retstr;
			break;
		case ',':
			comma = true;
			retstr = ',' + retstr;
			break;
		}
	}
	if (i >= 0) {
		if (comma) {
			var l = str.length;
			for (; i >= 0; i--) {
				retstr = str.substr(i, 1) + retstr;
				if (i > 0 && ((l - i) % 3) == 0)
					retstr = ',' + retstr;
			}
		} else
			retstr = str.substr(0, i + 1) + retstr;
	}

	retstr = retstr + '.';
	// 处理小数部分
	str = strarr.length > 1 ? strarr[1] : '';
	fmt = fmtarr.length > 1 ? fmtarr[1] : '';
	i = 0;
	for (var f = 0; f < fmt.length; f++) {
		switch (fmt.substr(f, 1)) {
		case '#':
			if (i < str.length)
				retstr += str.substr(i++, 1);
			break;
		case '0':
			if (i < str.length)
				retstr += str.substr(i++, 1);
			else
				retstr += '0';
			break;
		}
	}

	var rst = retstr.replace(/^,+/, '').replace(/.$/, '');
	// alert("res=="+rst);
	// $('#'+this.id).numberbox('setValue',rst);

	return rst;
}

function numberChar(num) {
	if (isNaN(num) || num > Math.pow(10, 12))
		return ""
	var cn = "零壹贰叁肆伍陆柒捌玖"
	var unit = new Array("拾百千", "分角")
	var unit1 = new Array("万亿", "")
	var numArray = num.toString().split(".")
	var start = new Array(numArray[0].length - 1, 2)

	function toChinese(num, index) {
		var num = num.replace(/\d/g, function($1) {
			return cn.charAt($1)
					+ unit[index].charAt(start-- % 4 ? start % 4 : -1)
		})
		return num
	}

	for (var i = 0; i < numArray.length; i++) {
		var tmp = ""
		for (var j = 0; j * 4 < numArray[i].length; j++) {
			var strIndex = numArray[i].length - (j + 1) * 4
			var str = numArray[i].substring(strIndex, strIndex + 4)
			var start = i ? 2 : str.length - 1
			var tmp1 = toChinese(str, i)
			tmp1 = tmp1.replace(/(零.)+/g, "零").replace(/零+$/, "")
			tmp1 = tmp1.replace(/^壹拾/, "拾")
			tmp = (tmp1 + unit1[i].charAt(j - 1)) + tmp
		}
		numArray[i] = tmp
	}

	numArray[1] = numArray[1] ? numArray[1] : ""
	numArray[0] = numArray[0] ? numArray[0] + "元" : numArray[0],
			numArray[1] = numArray[1].replace(/^零+/, "")
	numArray[1] = numArray[1].match(/分/) ? numArray[1] : numArray[1] + "整"
	return numArray[0] + numArray[1]
}
/*******************************************************************************
 * datagrid 列表数据显示 数字格式化
 ******************************************************************************/
/**
 * 单元格金额格式化， modifyed by baishuang on 20161201
 */
function datagridFormatNumberV2(num) {
	num = num + "";
	
	if (isNull(num)) {
		num = 0;
	}
	
	num = zeroFormat(num+"");// 去掉以0开头非个位数据
	if (isNaN(num) || num > Math.pow(10, 13)) {
		return "金额数据过大,最大限额拾万亿（拾兆）";
	}
	num = num.replace(new RegExp(/(,)/g), '');
	num = toNumber(num, '');
	return num;
}

function datagridFormatNumber(num) {
	num = num + "";
	
// if (num == null || num == '') {
// return "";
// }
	if (isNull(num)) {
		return "-";
	}
	
	num = zeroFormat(num+"");// 去掉以0开头非个位数据
	if (isNaN(num) || num > Math.pow(10, 13)) {
		return "金额数据过大,最大限额拾万亿（拾兆）";
	}
	num = num.replace(new RegExp(/(,)/g), '');
	num = toNumber(num, '');
	return num;
}

function castFormatNumber(num) {
	num = num + "";
	if (num == null || num == '') {
		return "";
	}
	num = zeroFormat(num+"");// 去掉以0开头非个位数据
	if (isNaN(num) || num > Math.pow(10, 13)) {
		return "金额数据过大,最大限额拾万亿（拾兆）";
	}
	num = num.replace(new RegExp(/(,)/g), '');
	num = toNumber(num, '#,###');
	return num;
}
function DX(n) { alert(1);
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n)) 
        return "数据非法"; 
    var unit = "千百拾亿千百拾万千百拾元角分", str = ""; 
        n += "00"; 
    var p = n.indexOf('.'); 
    if (p >= 0) 
        n = n.substring(0, p) + n.substr(p+1, 2); 
        unit = unit.substr(unit.length - n.length); 
    for (var i=0; i < n.length; i++) 
        str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i); 
    str = str.replace(/零(千|百|拾|角)/g, "零").replace(/(零)+/g, "零").replace(/零(万|亿|元)/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
    alert(str);
    return str;
}

function changeMoneyToChinese(money){
    var cnNums = new Array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"); // 汉字的数字
    var cnIntRadice = new Array("","拾","佰","仟"); // 基本单位
    var cnIntUnits = new Array("","万","亿","兆"); // 对应整数部分扩展单位
    var cnDecUnits = new Array("角","分","毫","厘"); // 对应小数部分单位
    var cnInteger = "整"; // 整数金额时后面跟的字符
    var cnIntLast = "元"; // 整型完以后的单位
    var maxNum = 999999999999999.9999; // 最大处理的数字
    
    var IntegerNum; // 金额整数部分
    var DecimalNum; // 金额小数部分
    var ChineseStr=""; // 输出的中文金额字符串
    var parts; // 分离金额后用的数组，预定义
    if( money == "" ){
        return "";
    }
    money = parseFloat(money);
    if( money >= maxNum ){
        $.alert('超出最大处理数字');
        return "";
    }
    if( money == 0 ){
        ChineseStr = cnNums[0]+cnIntLast+cnInteger;
        // document.getElementById("show").value=ChineseStr;
        return ChineseStr;
    }
    money = money.toString(); // 转换为字符串
    if( money.indexOf(".") == -1 ){
        IntegerNum = money;
        DecimalNum = '';
    }else{
        parts = money.split(".");
        IntegerNum = parts[0];
        DecimalNum = parts[1].substr(0,4);
    }
    if( parseInt(IntegerNum,10) > 0 ){// 获取整型部分转换
        zeroCount = 0;
        IntLen = IntegerNum.length;
        for( i=0;i<IntLen;i++ ){
            n = IntegerNum.substr(i,1);
            p = IntLen - i - 1;
            q = p / 4;
            m = p % 4;
            if( n == "0" ){
                zeroCount++;
            }else{
                if( zeroCount > 0 ){
                    ChineseStr += cnNums[0];
                }
                zeroCount = 0; // 归零
                ChineseStr += cnNums[parseInt(n)]+cnIntRadice[m];
            }
            if( m==0 && zeroCount<4 ){
                ChineseStr += cnIntUnits[q];
            }
        }
        ChineseStr += cnIntLast;
        // 整型部分处理完毕
    }
    if( DecimalNum!= '' ){// 小数部分
        decLen = DecimalNum.length;
        for( i=0; i<decLen; i++ ){
            n = DecimalNum.substr(i,1);
            if( n != '0' ){
                ChineseStr += cnNums[Number(n)]+cnDecUnits[i];
            }
        }
    }
    if( ChineseStr == '' ){
        ChineseStr += cnNums[0]+cnIntLast+cnInteger;
    }else if( DecimalNum == '' ){
        ChineseStr += cnInteger;
    }
    return ChineseStr;
}


// 只保留4位小数，如：2，会在2后面补上0000.即2.0000
function toDecimal4(x) {
	var f = parseFloat(x);
	if (isNaN(f)) {
		return false;
	}
	var f = Math.round(x * 100) / 100;
	var s = f.toString();
	var rs = s.indexOf('.');
	if (rs < 0) {
		rs = s.length;
		s += '.';
	}
	while (s.length <= rs + 4) {
		s += '0';
	}
	return s;
}
